package org.example.servlet;

import org.example.entity.User;
import org.example.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 服务器显示查询用户
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数
        String userid = req.getParameter("userid");
        String msg = "";
        if (userid != null) {
            User user = new User();
            user.setUserID(Integer.parseInt(userid));
            UserServiceImpl userService = new UserServiceImpl();
            User u = userService.queryOne(user);

            if (u != null) {
                System.out.println("根据ID，查询用户：" + u);
                msg += "查询成功：" + u.getUsername();
            } else {
                System.out.println("查询ID，失败！");
                msg += "查询失败：" + u;
            }

        }else {
            msg += "缺少必要的参数";
//            return; 用在if中表示终止执行
        }

        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.write(msg);
        out.flush();
        out.close();

        /**
         * Servlet中无法自定义业务方法，因为所有的Servlet都由Tomcat来实例化和调用
         * 我们可以利用Java中的反射机制，来实现自定义业务方法
         */
    }
}
